package com.example.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ruiji.common.CustomException;
import com.example.ruiji.dto.DishDto;
import com.example.ruiji.mapper.DishMapper;
import com.example.ruiji.pojo.*;
import com.example.ruiji.service.CategoryService;
import com.example.ruiji.service.DishFlavorService;
import com.example.ruiji.service.DishService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>  implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

@Autowired
private CategoryService categoryService;
    @Value("${reggie.path}")
    private String basePath;
@Override
@Transactional
    public void saveWithFlavor(DishDto dishDto) {
///需要保存两张表
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        //取出菜品ID
        Long id=dishDto.getId();

        //菜品口味入库
        List<DishFlavor> flavors=dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public R<Page> pagea(int page, int pageSize, String name) {
        Page<Dish> pageinfo=new Page<>(page,pageSize);

        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaUpdateWrapper<Dish> quer=new LambdaUpdateWrapper<>();
        quer.like(name!=null,Dish::getName,name);
        //添加排序条件
        quer.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        this.page(pageinfo,quer);
        //这个时候 pageinfo的值除了分类字符串 其余的都有了
        BeanUtils.copyProperties(pageinfo,dishDtoPage,"records");
        //records内的数据我们还需要转中 取出数据
        List<Dish> records=pageinfo.getRecords();
        //数据处理
        List<DishDto> list=records.stream().map(
                (item)->{
                    DishDto dishDto = new DishDto();
                    BeanUtils.copyProperties(item,dishDto);
                    Long categoryId=item.getCategoryId();
                    Category category = categoryService.getById(categoryId);
                    if(category!=null)
                    {
                        String categoryName=category.getName();
                        dishDto.setCategoryName(categoryName);
                    }
                    return dishDto;
                }

        ).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @Override
    public DishDto show(Long id) {
        ///1,查询基本菜品
    Dish dish=this.getById(id);

    DishDto dishDto=new DishDto();
        //2.查询基本口味
//条件构造器
        LambdaUpdateWrapper<DishFlavor> quer=new LambdaUpdateWrapper<>();
        quer.like(DishFlavor::getDishId,id);

        List<DishFlavor> list = dishFlavorService.list(quer);
        //3.封装  --拷贝过程
          BeanUtils.copyProperties(dish,dishDto);//dishDto 还剩下菜品

        dishDto.setFlavors(list);

    return dishDto;
    }

    @Override
    @Transactional
    public void savei(DishDto dishDto) {
    ///先添加dish表
        this.updateById(dishDto);

    //2.处理口味表 先删除再添加 用拷贝方式将口味每个组赋值菜品id
        LambdaUpdateWrapper<DishFlavor> quer=new LambdaUpdateWrapper<>();
        quer.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(quer);
        //再次添加
        List<DishFlavor> flavors = dishDto.getFlavors();
        //这个时间的菜品没有id 我们需要给与iD  --循环每个数组的元素 给每个数组的元素一个id 返回结果被collect接受 转换为list
        flavors=flavors.stream().map((
                item
                )->{
item.setDishId(dishDto.getId());
return item;
                }
        ).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);//批量保存数组
    }
    @Transactional
    @Override
    public void pldelet(List<Long> ids) {

    //删除的话 操作两张表 一张是商品表 还有一张是口味表
        //拿出商品id 根据商品id删除商品表
        //2.口味根据商品字段来删除
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
        //如果在售卖就不让删除
        queryWrapper.in(Dish::getId,ids);
        queryWrapper.eq(Dish::getStatus,1);
        int count=this.count(queryWrapper);

        if(count>0)
        {
            throw new CustomException("有套餐启售,无法删除");
        }
        //商品都是停售 删除开始
        LambdaQueryWrapper<Dish> queryWrapper2=new LambdaQueryWrapper();
        queryWrapper2.in(Dish::getId,ids);
        List<Dish> list = this.list(queryWrapper2);
        this.wenjrovm(list);

        this.removeByIds(ids);

        //删除口味表
        LambdaQueryWrapper<DishFlavor> queryWrapper1e=new LambdaQueryWrapper();
//根据dish_id删除
        queryWrapper1e.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(queryWrapper1e);

        //本地图片删除


    }
    public  void wenjrovm(List<Dish> list)
    {
        Iterator<Dish> iterator = list.iterator();
       while (iterator.hasNext())
       {
           Dish dish = iterator.next();
        String filePath = basePath+dish.getImage(); // 替换为实际的文件路径
// 创建文件对象
        File file = new File(filePath);
// 检查文件是否存在，并执行删除操作
        if (file.exists()) {
            if (file.delete()) {
                // 文件删除成功
             log.info("删除成功");
            } else {
                // 文件删除失败
                log.info("删除失败");
            }
        } else {
            // 文件不存在
            log.info("文件不存在");
        }
       }

    }

}
